# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ropls)
library(plyr)
library(magrittr)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

sampleLevels <- unique(sampleInfo$ClassNote)
sampleLevels

data <- read_csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = sampleLevels)) %>%
  arrange(ClassNote)

data

eachData <- data %>%
  column_to_rownames("SampleID")
x <- eachData %>%
  select(-c("ClassNote"))
y <- eachData$ClassNote %>%
  as.factor() #%>%
# as.numeric()
print(x)
print(y)

crossValI <- min(nrow(x), 7)
plsdaRs <- opls(x, y, orthoI = 1, permI = 1000, plotL = F, crossvalI = crossValI)
save(plsdaRs, file = "oplsda.RData")
print("in")
modelDf <- plsdaRs@modelDF %>%
  rownames_to_column("poName") %>%
  mutate(poName = poName %>%
    str_replace("p1", "P1") %>%
    str_replace("o1", "O1")) %>%
  column_to_rownames("poName")

r2xCum <- modelDf["sum", "R2X(cum)"]
modelDf["sum", "R2X(cum)"] = modelDf["sum", "R2X"]
modelDf["sum", "R2X"] = r2xCum

r2yCum <- modelDf["sum", "R2Y(cum)"]
modelDf["sum", "R2Y(cum)"] = modelDf["sum", "R2Y"]
modelDf["sum", "R2Y"] = r2yCum
modelDf["O1", "R2Y(cum)"] = r2yCum

q2Cum <- modelDf["sum", "Q2(cum)"]
modelDf["sum", "Q2(cum)"] = modelDf["sum", "Q2"]
modelDf["sum", "Q2"] = q2Cum
modelDf["O1", "Q2(cum)"] = q2Cum

scoreMN <- plsdaRs@scoreMN %>%
  as.data.frame() %>%
  rownames_to_column("SampleID")
orthoScoreMN <- plsdaRs@orthoScoreMN %>%
  as.data.frame() %>%
  rownames_to_column("SampleID")
plotData <- scoreMN %>%
  inner_join(orthoScoreMN, by = c("SampleID")) %>%
  rename_at(vars(-c("SampleID")), function(x) {
    x %>%
      str_replace("p1", "P1") %>%
      str_replace("o1", "O1")
  }) %>%
  column_to_rownames("SampleID")
plotData
parent <- paste0("./")
createWhenNoExist(parent)
modeFileName <- paste0(parent, "/OPLSDA_R2X_R2Y_Q2.csv")
dataFileName <- paste0(parent, "/OPLSDA_Score.csv")
write.csv(plotData, dataFileName)

outModelDf <- modelDf %>%
  rownames_to_column("poName") %>%
  rename(` ` = poName) %>%
  select(-c("Signif."))

outModelDf

write_csv(outModelDf, modeFileName)




